package org.example.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NIOServer {
    // NIO中的核心
    // channel
    // buffer
    // selector

    public static void main(String[] args) {
        ServerSocketChannel serverSocketChannel;
        try {
            serverSocketChannel = ServerSocketChannel.open();
//            serverSocketChannel.configureBlocking(false); //设置非阻塞
            serverSocketChannel.socket().bind(new InetSocketAddress(8088));
            while(true){
                // 不断轮询
                SocketChannel socketChannel = serverSocketChannel.accept();
                if(socketChannel != null){

                    System.out.println("客户已连接：" + socketChannel.getLocalAddress());
                    Thread.sleep(10000);
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    socketChannel.read(byteBuffer);
                    byteBuffer.flip();
                    socketChannel.write(byteBuffer);

                }else {
                    Thread.sleep(1000);
                    System.out.println("连接未就绪");
                }
            }

        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
